<template>
  <div>
    <FormCreate v-if="visible" v-model="tableForm" :rule="totalRules" :value.sync="formValue" :option="options" @file="fileChange" />
    <!--<ElButton type="primary" aligen="center" plain @click="submit">同意</ElButton>-->
    <!--<ElButton aligen="center" plain @click="reset">不同意</ElButton>-->
  </div>
</template>

<script>
import request from '@/utils/request'
import { getFormData, startProcess } from '@/api/flowable'
export default {
  data() {
    return {
      src: null,
      visible: false,
      iframeHeight: '',
      tableForm: {},
      formValue: {},
      tableFields: [],
      key: '',
      options: {
        submitBtn: false,
        resetBtn: false,
        onSubmit: (formData) => {
          alert(JSON.stringify(formData))
        },
        global: {
          '*': {
            props: {
              disabled: true,
            },
            col: {
              span: 12,
            },
          },
          upload: {
            props: {
              onError: function(r) {
                alert('上传失败')
              },
            },
          },
        },
      },
      rule: [],
      extendsRules: [],
      totalRules: [],
      processDefinitionId: '',
      formId: '',
      name: '',
      orgCode: '',
      fileList: [],
      attachments: [],
      attachmentsValue: [],
      sceneCode: '',
      processType: '',
    }
  },
  created() {
    this.$nextTick(() => {
      const deviceHeight = document.documentElement.clientHeight
      this.iframeHeight = deviceHeight + 'px'
    })
  },
  methods: {
    async init(val) {
      this.rule = []
      this.totalRules = this.rule
      this.visible = true

      const { code, data } = await getFormData(val.processDefinitionId)
      if (code == '200') {
        const json = JSON.parse(data.modelEditorJson)
        this.tableFields = json.fields
        for (const item of this.tableFields) {
          if (item.type == 'upload') {
            this.extendsRules.push({
              type: 'upload',
              field: item.id,
              title: item.name,
              value: this.attachmentsValue,
              props: {
                type: 'select',
                action: '',
                listType: 'text',
                showFileList: true,
                autoUpload: false,
                // headers: { Authorization: getToken(), user: getUserName() },
                name: 'file',
                httpRequest: (content) => {
                  console.log('手动提交文件')
                },
                multiple: true,
                onSuccess: (res, file, fileList) => {
                  const content = res.content
                  this.attachmentsValue.push(content.attName)
                },
                onChange: (file, fileList) => {
                  // this.attachments = fileList
                  this.length = document.querySelector('input[type=file]').files.length
                  if (this.length > 0) {
                    Array.from(document.querySelector('input[type=file]').files).forEach((file) => {
                      if (this.attachments.indexOf(file) == -1) {
                        this.attachments.push(file)
                      }
                    })
                  }
                  return false
                },
                onRemove: function(file, fileList) {
                  this.attachments = fileList
                },
              },
              col: {
                span: 24,
              },
            })
          } else if (item.type == 'multi-line-text') {
            this.extendsRules.push({
              type: 'input',
              field: item.id,
              title: item.name,
              props: {
                type: 'textarea',
                rows: 5,
              },
              col: {
                span: 24,
              },
            })
          } else if (item.type == 'radio-buttons') {
            this.extendsRules.push({
              type: 'checkbox',
              field: item.id,
              title: item.name,
              value: ['1', '2', '3'],
              options: [
                { value: '1', label: '好用', disabled: true },
                { value: '2', label: '方便', disabled: false },
                { value: '3', label: '实用', disabled: false },
                { value: '4', label: '有效', disabled: false },
              ],
            })
          } else if (item.type == 'dropdown') {
            // request({
            //   url: `/business/dict/item/select/${item.placeholder}`,
            //   params: {
            //     multiple: this.multiple == null ? null : 1
            //   }
            // }).then((response) => {
            //   this.options = response.data.content
            // })
            this.extendsRules.push({
              type: 'select',
              field: item.id,
              title: item.name,
              // value: "104",
              col: {
                span: 12,
              },
              props: {
                multiple: false,
              },
              options: item.params.options,
            })
          } else if (item.type == 'date') {
            this.extendsRules.push({
              type: 'DatePicker',
              field: item.id,
              title: item.name,
              value: [],
              props: {
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                placeholder: '请选择活动日期',
              },
            })
          } else {
            this.extendsRules.push({
              type: 'input',
              field: item.id,
              title: item.name,
            })
          }
        }
        this.totalRules = this.rule.concat(this.extendsRules)
        this.formValue = val.processVariables
      }
    },
    async submitData(formData) {
      const { code } = await startProcess(this.processDefinitionId, formData)
      this.visible = false
    },
    submit() {
      this.tableForm.submit((formData1, $f) => {
        const formData = new FormData()
        console.log(this.attachments)
        if (this.attachments.length > 0) {
          this.attachments.forEach((file) => {
            formData.append('files', file)
          })

          //	走接口
          console.log(formData.getAll('files'))
          const _url = '*****' // 上传文件接口地址
          request({
            url: '/user/fast/demo/upload/fileMultiples',
            method: 'post',
            data: formData,
          }).then(
            (res) => {
              console.log(res)
              // 此处重置文件中间存储变量是为了相同文件能够重复传递
              if (res.data.code == '200') {
                // this.$message.success(`成功`);
                const formData = this.tableForm.form
                formData['attachment'] = res.data.content
                this.submitData(formData)
              } else {
                this.$message.success(`失败`)
              }
            },
            (err) => {
              this.attachments = []
              this.$message.success(`失败`)
            }
          )
        } else {
          this.submitData(formData1)
        }
      })
    },
    reset() {
      this.tableForm.resetFields()
    },
    closed() {
      this.visible = false
      this.extendsRules = []
      this.totalRules = []
    },
    fileChange() {
      console.log('触发监听事件')
    },
    // 上传文件用到的两个方法

    change() {
      // 判断上传文件数量
      this.length = document.querySelector('input[type=file]').files.length
      if (this.length > 0) {
        Array.from(document.querySelector('input[type=file]').files).forEach((file) => {
          if (this.fileList.indexOf(file) == -1) {
            this.fileList.push(file)
          }
        })
      }
      return false
    },
  },
}
</script>

<style>
.ideskForm textarea {
  width: 100%;
}
.ideskForm .el-select {
  width: 100%;
}
.ideskForm .el-date-editor {
  width: 100%;
}
</style>
